package config

import (
	"io/ioutil"
	"os"
	"time"

	"github.com/go-kit/kit/log"
	"github.com/pelletier/go-toml"
)

// ConfigFile 服务配置对象定义
type ConfigFile struct {
	Common   *CommonConfig      `toml:"common"`
	Adapters map[string]Adapter `toml:"adapters"`
}

// CommonConfig 服务通用配置部分
type CommonConfig struct {
	ListenHost       string        `toml:"listen-host"`
	HTTPPort         string        `toml:"http-port"`
	HTTPCACert       string        `toml:"http-ca-cert"`
	HTTPCert         string        `toml:"http-cert"`
	HTTPKey          string        `toml:"http-key"`
	VerifyClientCert bool          `toml:"verify-client-cert"`
	SRDETCDServers   string        `toml:"srd-etcd-servers"`
	SRDETCDCaCert    string        `toml:"srd-etcd-ca-cert"`
	SRDETCDCert      string        `toml:"srd-etcd-cert"`
	SRDETCDKey       string        `toml:"srd-etcd-key"`
	SRDPrefix        string        `toml:"srd-prefix"`
	AdapterDir       string        `toml:"adapter-dir"`
	GracefulTimeout  time.Duration `toml:"graceful-timeout"`
}

// Adapter 适配器对象
type Adapter struct {
	PrefixURI string             `toml:"prefix-uri"`
	Version   string             `toml:"version"`
	Hystries  map[string]Hystrix `toml:"hystries"`
}

// Hystrix 熔断配置对象
type Hystrix struct {
	Timeout                int `toml:"timeout"`
	SleepWindow            int `toml:"sleep-window"`
	ErrorPercentThreshold  int `toml:"error-percent-threshold"`
	MaxConcurrentRequests  int `toml:"max-concurrent-requests"`
	RequestVolumeThreshold int `toml:"request-volume-threshold"`
}

// ParseConfigFile 解析配置文件方法
func ParseConfigFile(filePath string, logger log.Logger) *ConfigFile {
	var conf ConfigFile
	fs, err := ioutil.ReadFile(filePath)
	if err != nil {
		logger.Log("config file with TOML format not found", err)
		os.Exit(1)
	}
	if err := toml.Unmarshal(fs, &conf); err != nil {
		logger.Log("config file with TOML format parse fail", err)
		os.Exit(1)
	}
	return &conf
}
